package logic

import (
	"context"
	"encoding/json"
	"shopexam/model/mysql"
	"shopexam/model/redis"
	"strconv"
	"time"

	"shopexam/shoprpc/internal/svc"
	"shopexam/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *shoprpc.ShopListRequest) (*shoprpc.ShopListResponse, error) {
	// todo: add your logic here and delete this line
	var shop []mysql.Products
	var list1 []*shoprpc.ShopList
	key := "list" + strconv.Itoa(int(in.Page)) + strconv.Itoa(int(in.Size)) + in.Name
	result, err := redis.Rdb.Get(key).Result()
	if err != nil {
		query := mysql.DB.Debug()
		if in.Name != "" {
			query = query.Where("name like = ?", "%"+in.Name+"%")
		}
		if in.Page != 0 && in.Size != 0 {
			query = query.Order("price desc").Order("created_at desc").Offset(int((in.Page - 1) * in.Size)).Limit(int(in.Size)).Find(&shop)
		}
		marshal, _ := json.Marshal(&shop)
		redis.Rdb.Set(key, string(marshal), time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &shop)
	}
	for _, shops := range shop {
		list2 := shoprpc.ShopList{
			Nums:     shops.Nums,
			Name:     shops.Name,
			Price:    float32(shops.Price),
			OldPrice: float32(shops.OldPrice),
			Image:    shops.Image,
			Intro:    shops.Intro,
			UserId:   int64(shops.UserId),
		}
		list1 = append(list1, &list2)
	}
	return &shoprpc.ShopListResponse{List: list1}, nil
}
